import Sortable from "sortablejs";
import { transformI18n } from "@/plugins/i18n";
import { useEpThemeStoreHook } from "@/store/modules/epTheme";
import { useRenderIcon } from "@/components/ReIcon/src/hooks";

import { UserFieldsController} from "@/api/system";
import {
  type PropType,
  ref,
  unref,
  computed,toRaw,
  nextTick,
  defineComponent,
  getCurrentInstance
} from "vue";
import {
  delay,
  cloneDeep,
  isBoolean,
  isFunction,storageLocal,
  getKeyList
} from "@pureadmin/utils";

import Fullscreen from "@iconify-icons/ri/fullscreen-fill";
import ExitFullscreen from "@iconify-icons/ri/fullscreen-exit-fill";
import DragIcon from "@/assets/table-bar/drag.svg?component";
import ExpandIcon from "@/assets/table-bar/expand.svg?component";
import RefreshIcon from "@/assets/table-bar/refresh.svg?component";
import SettingIcon from "@/assets/table-bar/settings.svg?component";
import CollapseIcon from "@/assets/table-bar/collapse.svg?component";
import {message} from "@/utils/message";


const props = {
  /** 头部最左边的标题 */
  title: {
    type: String,
    default: "列表"
  },
  tableName: {
    type: String,
    default: ""
  },
  /** 对于树形表格，如果想启用展开和折叠功能，传入当前表格的ref即可 */
  tableRef: {
    type: Object as PropType<any>
  },
  /** 需要展示的列 */
  columns: {
    type: Array as PropType<TableColumnList>,
    default: () => []
  },
  isExpandAll: {
    type: Boolean,
    default: false
  },
  showColumnsSet: {
    type: Boolean,
    default: false
  },
  tableKey: {
    type: [String, Number] as PropType<string | number>,
    default: "0"
  }
};

export default defineComponent({
  name: "PureTableBar",
  props,
  emits: ["refresh", "fullscreen"],
  setup(props, { emit, slots, attrs }) {
    const size = ref("small");
    const loading = ref(false);
    const checkAll = ref(true);
    const isFullscreen = ref(false);
    const isIndeterminate = ref(false);
    const instance = getCurrentInstance()!;
    const isExpandAll = ref(props.isExpandAll);
    const column_visible = ref(true);
    const showColumnsSet = ref(props.showColumnsSet);
    //获取数据库中的用户数据
    const columsViewSetList = ref(props?.columns||[]) //可以选的列表
    const checkColumnListOrder = ref(getKeyList(cloneDeep(props?.columns), "label"));//右侧排序已选待排序的
    const dynamicColumns = ref(cloneDeep(columsViewSetList.value));
    const checkedColumns = ref([]);

    const resetColumnListOrder = ref([]);//记录重置状态
    const resetDynamicColumns = ref([]);//记录重置状态
    const resetColumsViewSetList = ref([]);//记录重置状态
    const resetCheckedColumns = ref([]);//记录重置状态
    if(props.tableName != ''){
     UserFieldsController(toRaw({view_type:props.tableName})).then(function (res){
       columsViewSetList.value = props?.columns.filter(x=>res.data.fields_all.includes(x.label))
       const yLabel = props?.columns.map(y=>y.label)
       checkColumnListOrder.value = res.data.select.filter(x=>yLabel.includes(x))
       checkedColumns.value = res.data.select.filter(x=>yLabel.includes(x))
       // 1. 提取匹配项并按优先级排序
       const matchedItems = checkColumnListOrder.value.map(label =>
         columsViewSetList.value.find(item => item.label === label)
       ).filter(Boolean); // 过滤掉undefined（未找到的项）
       // 2. 提取未匹配项（保持原顺序）
       const unmatchedItems = columsViewSetList.value.filter(item =>
         !checkColumnListOrder.value.includes(item.label)
       );
        // 3. 合并排好顺序的结果
       dynamicColumns.value = [...matchedItems, ...unmatchedItems];
       //保留重置状态
       resetColumnListOrder.value = cloneDeep(checkColumnListOrder.value)
       resetDynamicColumns.value = cloneDeep(dynamicColumns.value)
       resetColumsViewSetList.value = cloneDeep(columsViewSetList.value)
       resetCheckedColumns.value = cloneDeep(checkedColumns.value)
      })
    }
    // const filterColumns = cloneDeep(columsViewSetList.value).filter(column =>
    //   isBoolean(column?.hide)
    //     ? !column.hide
    //     : !(isFunction(column?.hide) && column?.hide())
    // );



    const getDropdownItemStyle = computed(() => {
      return s => {
        return {
          background:
            s === size.value ? useEpThemeStoreHook().epThemeColor : "",
          color: s === size.value ? "#fff" : "var(--el-text-color-primary)"
        };
      };
    });

    const iconClass = computed(() => {
      return [
        "text-black",
        "dark:text-white",
        "duration-100",
        "hover:!text-primary",
        "cursor-pointer",
        "outline-none"
      ];
    });

    const topClass = computed(() => {
      return [
        "flex",
        "justify-between",
        "pt-[3px]",
        "px-[11px]",
        "border-b-[1px]",
        "border-solid",
        "border-[#dcdfe6]",
        "dark:border-[#303030]"
      ];
    });

    function onReFresh() {
      loading.value = true;
      emit("refresh");
      delay(500).then(() => (loading.value = false));
    }

    function onExpand() {
      isExpandAll.value = !isExpandAll.value;
      toggleRowExpansionAll(props.tableRef.data, isExpandAll.value);
      storageLocal().setItem("expand_"+props.tableName, isExpandAll.value);
    }

    function onFullscreen() {
      isFullscreen.value = !isFullscreen.value;
      emit("fullscreen", isFullscreen.value);
    }

    function toggleRowExpansionAll(data, isExpansion) {
      data.forEach(item => {
        props.tableRef.toggleRowExpansion(item, isExpansion);
        if (item.children !== undefined && item.children !== null) {
          toggleRowExpansionAll(item.children, isExpansion);
        }
      });
    }

    //全选，反选
    function handleCheckAllChange(val: boolean) {
      checkedColumns.value = val ? checkColumnListOrder.value : columsViewSetList.value.filter(x=>x.disabled!=undefined && x.disabled).map(x=>x.label) ;
      isIndeterminate.value = false;
      console.log(44444,columsViewSetList.value,4444411,checkedColumns.value)
      dynamicColumns.value.map(column =>
        (val || Object.values(checkedColumns.value).includes(column.label)) ? (column.hide = false) : (column.hide = true )
      );
    }

    //勾选某一个时的事件
    function handleCheckedColumnsChange(value: string[]) {
      checkedColumns.value = value;
      const checkedCount = value.length;
      checkAll.value = checkedCount === checkColumnListOrder.value.length;
      isIndeterminate.value =
        checkedCount > 0 && checkedCount < checkColumnListOrder.value.length;
    }

    //右侧复选框勾选
    function handleCheckColumnListChange(val: boolean, label: string) {
      // dynamicColumns.value = cloneDeep(props?.columns);
      const existLabels = dynamicColumns.value.map(x=>x.label);
      console.log(5555,existLabels,label,val,555666,checkedColumns.value)
      if(!existLabels.includes(label) && val){
        dynamicColumns.value= columsViewSetList.value.filter(x=>checkedColumns.value.includes(x.label))
      }
      dynamicColumns.value.filter(item => transformI18n(item.label) === transformI18n(label))[0].hide = !val;
      //移去右边排序的
      if(val){
        //重新勾选的放到最后，且动态列中重新排序
        checkColumnListOrder.value.push(label)

        //重新排序
        // 1. 提取匹配项并按优先级排序
        const matchedItems = checkColumnListOrder.value.map(label => columsViewSetList.value.find(item => item.label === label)).filter(Boolean); // 过滤掉undefined（未找到的项）
        // 2. 提取未匹配项（保持原顺序）
        const unmatchedItems = columsViewSetList.value.filter(item => !checkColumnListOrder.value.includes(item.label));
        // 3. 合并排好顺序的结果
        dynamicColumns.value = [...matchedItems, ...unmatchedItems];

      }else{
        const index0 = checkColumnListOrder.value.indexOf(label);
        if (index0 !== -1) {
          checkColumnListOrder.value.splice(index0, 1); // 从索引位置删除 1 个元素
        }
      }
    }
    //右边排序删除掉一个
    function handleCheckColumnListDeleteOne( label: string) {
      const val2 = false
      dynamicColumns.value.filter(
        item => transformI18n(item.label) === transformI18n(label)
      )[0].hide = !val2;
      //移去右边排序的
      // const index = checkColumnListOrder.value.indexOf(label);
      // if (index !== -1) {
      //   checkColumnListOrder.value.splice(index, 1); // 从索引位置删除 1 个元素
      // }
    }

    async function onReset() {
      checkColumnListOrder.value = cloneDeep(resetColumnListOrder.value)
      dynamicColumns.value = cloneDeep(resetDynamicColumns.value)
      columsViewSetList.value = cloneDeep(resetColumsViewSetList.value)
      checkedColumns.value = cloneDeep(resetCheckedColumns.value)
    }

    async function onSave() {
      UserFieldsController({view_type:props.tableName,fields:checkColumnListOrder.value},"post").then(function (res){
        message(`列字段设置成功`, { type: "success" });
        setTimeout(() => {column_visible.value = false;}, 1000);
        emit("refresh");
      })
    }

    const dropdown = {
      dropdown: () => (
        <el-dropdown-menu class="translation">
          <el-dropdown-item style={getDropdownItemStyle.value("large")} onClick={() => (size.value = "large")}>宽松</el-dropdown-item>
          <el-dropdown-item style={getDropdownItemStyle.value("default")} onClick={() => (size.value = "default")}>默认</el-dropdown-item>
          <el-dropdown-item style={getDropdownItemStyle.value("small")} onClick={() => (size.value = "small")}>紧凑</el-dropdown-item>
        </el-dropdown-menu>
      )
    };

    /** 列展示拖拽排序 */
    const rowDrop = (event: { preventDefault: () => void }) => {
      event.preventDefault();
      nextTick(() => {
        const wrapper: HTMLElement = ( instance?.proxy?.$refs[`GroupRef${unref(props.tableKey)}`] as any ).$el.firstElementChild;
        Sortable.create(wrapper, {
          animation: 300,
          handle: ".drag-btn",
          onEnd: ({ newIndex, oldIndex, item }) => {
            const targetThElem = item;
            const wrapperElem = targetThElem.parentNode as HTMLElement;

            const oldColumn = dynamicColumns.value.find(x=>x.label==checkColumnListOrder.value[oldIndex]);
            const newColumn = dynamicColumns.value.find(x=>x.label==checkColumnListOrder.value[newIndex]);
            // console.log(4444000,checkColumnListOrder.value,oldColumn,newColumn,newIndex, oldIndex,item,)
            // 当前列存在fixed属性或disabled属性 则不可拖拽
            if (oldColumn?.fixed || newColumn?.fixed||oldColumn?.disabled!==true || newColumn?.disabled!==true) {
              const oldThElem = wrapperElem.children[oldIndex] as HTMLElement;
              if (newIndex > oldIndex) {
                wrapperElem.insertBefore(targetThElem, oldThElem);
              } else {
                wrapperElem.insertBefore(
                  targetThElem,
                  oldThElem ? oldThElem.nextElementSibling : oldThElem
                );
              }
              //dynamicColumns要交换的位置
              const indexOld = dynamicColumns.value.findIndex(item => item.label === checkColumnListOrder.value[oldIndex]);
              const indexNew = dynamicColumns.value.findIndex(item => item.label === checkColumnListOrder.value[newIndex]);

              const currentRowRight = checkColumnListOrder.value.splice(oldIndex, 1)[0];
              checkColumnListOrder.value.splice(newIndex, 0, currentRowRight);

              const currentRow = dynamicColumns.value.splice(indexOld, 1)[0];
              dynamicColumns.value.splice(indexNew, 0, currentRow);
              return;
            }
          }
        });
      });
    };

    const isFixedColumn = (label: string) => {
      return dynamicColumns.value.filter(item => transformI18n(item.label) === transformI18n(label))[0]?.disabled ? true : false;
      // return dynamicColumns.value.filter(item => transformI18n(item.label) === transformI18n(label))[0]?.fixed ? true : false;
    };

    const rendTippyProps = (content: string) => {
      // https://vue-tippy.netlify.app/props
      return {
        content,
        offset: [0, 18],
        duration: [300, 0],
        followCursor: true,
        hideOnClick: "toggle"
      };
    };



    const reference = {
      reference: () => !showColumnsSet.value ? (<span style="display:none"/>) :(
        <SettingIcon class={["w-[16px]", iconClass.value]} v-tippy={rendTippyProps("列设置")} onClick={() => column_visible.value=true} />
      )
    };

    return () => (
      <>
        <div {...attrs} class={["w-[99/100]","px-2","pb-2","bg-bg_color",isFullscreen.value? ["!w-full", "!h-full", "z-[2002]", "fixed", "inset-0"]:"mt-2"]} >
          <div class="flex justify-between w-full p-2">
            {slots?.title ? (slots.title()) : (<p class="font-bold truncate">{props.title}</p>)}

            <div className="flex items-center justify-around">
              {slots?.buttons ? (
                <div className="flex mr-4">{slots.buttons()}</div>
              ) : null}
              {props.tableRef?.size ? (
                <>
                  <ExpandIcon
                    class={["w-[16px]", iconClass.value]}
                    style={{
                      transform: isExpandAll.value ? "none" : "rotate(-90deg)"
                    }}
                    v-tippy={rendTippyProps(
                      isExpandAll.value ? "折叠" : "展开"
                    )}
                    onClick={() => onExpand()}
                  />
                  <el-divider direction="vertical"/>
                </>
              ) : null}
              <RefreshIcon class={["w-[16px]", iconClass.value, loading.value ? "animate-spin" : ""]}
                v-tippy={rendTippyProps("刷新")} onClick={() => onReFresh()}
              />
              <el-divider direction="vertical"/>
              <el-dropdown v-slots={dropdown} trigger="click" v-tippy={rendTippyProps("密度")}>
                <CollapseIcon class={["w-[16px]", iconClass.value]}/>
              </el-dropdown>
              {!showColumnsSet.value ? (null) :(<el-divider direction="vertical"/>)}
              <el-popover v-slots={reference} placement="bottom-start" popper-style={{padding: 0}} width="800" trigger="click">
                <el-row v-show={column_visible.value}>
                  <el-col span={18} style="padding:20px;">
                    <el-col span={24}  style="margin-bottom:20px;"><b>设置展示列{column_visible.value}</b></el-col>
                      <div className="pt-[6px] pl-[20px]">
                        <el-scrollbar style="height:300px;">
                          <el-checkbox-group ref={`GroupRef${unref(props.tableKey)}`} modelValue={checkedColumns.value} onChange={value => handleCheckedColumnsChange(value)}>
                              {columsViewSetList.value.map(x=>x.label).map((item, index) => {
                                return (
                                    <el-checkbox key={index} label={item} value={item} disabled={isFixedColumn(item)}
                                      onChange={value => handleCheckColumnListChange(value, item)}>
                                      <span title={transformI18n(item)} className="inline-block w-[120px] truncate hover:text-text_color_primary">
                                        {transformI18n(item)}
                                      </span>
                                    </el-checkbox>
                                );
                              })}
                          </el-checkbox-group>
                        </el-scrollbar>
                      </div>
                      <div className={[topClass.value]} style="margin-top:20px;">
                        {/*<el-checkbox label="全选/反选"  v-model={checkAll.value} indeterminate={isIndeterminate.value}*/}
                        {/*  onChange={value => handleCheckAllChange(value)} />*/}
                        <el-button type="info" style="margin-left:10px;"  onClick={() => onReset()}>重置</el-button>
                        <el-button type="primary" style="margin-left:10px;"  onClick={() => onSave()}>保存</el-button>
                      </div>
                  </el-col>

                  <el-col  span={6} style="border-left:1px solid #ccc">
                    <div style="padding:8px">当前选定的列</div>
                    <div className="pt-[6px] pl-[11px]">
                      <el-scrollbar max-height="48vh">
                        <el-checkbox-group ref={`GroupRef${unref(props.tableKey)}`} modelValue={checkedColumns.value}
                          onChange={value => handleCheckedColumnsChange(value)}>
                          <el-space direction="vertical" alignment="flex-start" size={0}>
                            {checkColumnListOrder.value.map((item, index) => {
                              return (
                                <div className="flex items-center">
                                  {/*<DragIcon class={[ "drag-btn w-[16px] mr-2", isFixedColumn(item) ? "!cursor-no-drop" : "!cursor-grab"]}*/}
                                  {/*  onMouseenter={(event) => {*/}
                                  {/*    if (!isFixedColumn(item)) {*/}
                                  {/*      rowDrop(event);*/}
                                  {/*    } else {*/}
                                  {/*      event.preventDefault(); // 可选：阻止默认行为*/}
                                  {/*    }*/}
                                  {/*  }}*/}
                                  {/*/>*/}
                                  {isFixedColumn(item)?'':<DragIcon class="drag-btn w-[16px] mr-2 !cursor-grab" onMouseenter={(event) => rowDrop(event)}/>}

                                  <el-checkbox key={index} label={item} value={item} disabled={isFixedColumn(item)}
                                    onChange={value =>handleCheckColumnListChange(value, item)} >
                                  <span title={transformI18n(item)} className="inline-block w-[100px] truncate hover:text-text_color_primary">
                                    {transformI18n(item)}
                                  </span>
                                    {isFixedColumn(item)?'':<span style="padding:0;border:0"   onClick={i=>handleCheckColumnListDeleteOne( item)}>delete</span>}
                                  </el-checkbox>
                                </div>
                              );
                            })}
                          </el-space>
                        </el-checkbox-group>
                      </el-scrollbar>
                    </div>
                  </el-col>
                </el-row>
              </el-popover>
              <el-divider direction="vertical"/>

              <iconifyIconOffline className={["w-[16px]", iconClass.value]} icon={isFullscreen.value ? ExitFullscreen : Fullscreen} v-tippy={isFullscreen.value ? "退出全屏" : "全屏"} onClick={() => onFullscreen()}/>
            </div>
          </div>
          {slots.default({
            size: size.value,
            dynamicColumns: dynamicColumns.value
          })}
        </div>
      </>
    );
  }
});
